// pages/detail/detail.js

// 工具函数 - 写在页面 JS 文件顶部或 utils 工具类中
function formatTime(postTimeStr) {
  // 处理 iOS/Safari 兼容性问题
  const postDate = new Date(postTimeStr.replace(' ', 'T'));
  const now = new Date();
  const diff = now - postDate;

  // 未来时间直接返回完整格式
  if (diff < 0) return formatFullDate(postDate);

  const seconds = Math.floor(diff / 1000);
  const minutes = Math.floor(seconds / 60);
  const hours = Math.floor(minutes / 60);

  if (seconds < 60) return `${seconds}秒前`;
  if (minutes < 60) return `${minutes}分钟前`;
  if (hours < 24) return `${hours}小时前`;
  return formatFullDate(postDate);
}

function formatFullDate(date) {
  const year = date.getFullYear();
  const month = (date.getMonth() + 1).toString().padStart(2, '0');
  const day = date.getDate().toString().padStart(2, '0');
  return year !== new Date().getFullYear() 
    ? `${year}年${month}月${day}日` 
    : `${month}月${day}日`;
}

Page({
  data: {
    postId:null,
    uid:null,
    avatar:null,
    nickname:null,
    content:null,
    urls:null,
    liked:null,
    disliked:null,
    like_count:null,
    act:null,
    review_count:null,
    review_list:[],
    com_content:null,
    formatTime:0,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    let pid = options.pid;
    let uid = options.uid;
    const that = this;
    this.setData({
      postId:pid,
      uid:uid
    });
    wx.request({
      url:`http://127.0.0.1:3527/posts/findone?pid=${pid}&uid=${uid}`,
      method:'GET',
      success(res){
        let info = res.data.data[0];
        console.log(info);
        that.setData({
          postId:info.post_id,
          uid:info.user_id,
          avatar:info.avatar,
          nickname:info.nickname,
          content:info.content,
          urls:info.urls,
          liked:info.liked,
          disliked:info.disliked,
          like_count:info.like_count,
          review_count:info.review_count,
          act:info.act,
          formatTime:formatTime(info.post_time)
        });
      }
    })
    wx.request({
      url: `http://127.0.0.1:3527/reviews/get/${pid}`,
      method:'GET',
      success(res){
        const processedList = res.data.data.map(item => {
          console.log(item);
          return {
            ...item, // 保留原始字段
            formatTime: formatTime(item.review_time) // 添加格式化时间字段
          };
        });
        that.setData({
          review_list:processedList
        })
      }
    })
  },

  onClickLeft(){
    wx.reLaunch({
      url: '/pages/index/index',
    })
  },

  
  addLike(id,useful,cancel){
    let that = this;
    let uid = this.data.uid;
    let pid = this.data.postId;
    let act = this.data.act;
    console.log("((((((((((((((((")
    console.log(this.data.like_count);
    if (useful === 1){
      wx.request({
        url:'http://127.0.0.1:3527/posts/like',
        method:'PUT',
        data:{
          "post_id":pid,
          "user_id":wx.getStorageSync('uid'),
          "like":1,
          "dislike":0,
          "act":act,
          "cancel":cancel
        },
      });
    } else if (useful === -1){
      wx.request({
        url:'http://127.0.0.1:3527/posts/like',
        method:'PUT',
        data:{
          "post_id":pid,
          "user_id":wx.getStorageSync('uid'),
          "like":0,
          "dislike":1,
          "act":act,
          "cancel":cancel
        },
      })
    } else{
      wx.request({
        url:'http://127.0.0.1:3527/posts/like',
        method:'PUT',
        data:{
          "post_id":pid,
          "user_id":wx.getStorageSync('uid'),
          "like":0,
          "dislike":0,
          "act":act,
          "cancel":cancel
        },
      });
    };
    that.setData({act:1});
  },
  // 点赞处理
  likePost(e) {
    let that = this;
    let like_count = this.data.like_count;
    console.log(like_count);
    if (this.data.liked){
      console.log("+++++++++++++++++++++++++")
      this.addLike(this.data.post_id,0,true);
      that.setData({
        liked:false,
        like_count:like_count-1
      })
    } else{
      this.addLike(this.data.post_id,1,false);
      that.setData({
        liked:true,
        disliked:false,
        like_count:like_count+1
      })
    }
  },

  dislikePost(e) {
    let that = this;
    let like_count = this.data.like_count;
    let liked = this.data.liked;
    if (this.data.disliked){
      this.addLike(this.data.post_id,0,false);
      that.setData({
        disliked:false
      })
      console.log("*******************");
    } else{
      this.addLike(this.data.post_id,-1,this.data.liked);
      that.setData({
        liked:false,
        disliked:true,
        like_count: liked ? like_count-1 : like_count
      })
    }
  },

   // 点击评论按钮
   toComments(e) {
    let postId = e.currentTarget.dataset.post_id;
    let nickname = e.currentTarget.dataset.nickname; 
    let content = e.currentTarget.dataset.content
    this.setData({
      showCommentPopup: true,
      currentPostId: postId,  // 动态更新当前帖子ID
      currentNickname:nickname,
      currentContent:content
    });
  },

  onInputChange(e){
    this.setData({
      com_content: e.detail.value
    });
    console.log(this.data.com_content);
  },

  onSub(){
    console.log(this.data.com_content);
    let that = this;
    let pid = this.data.postId;
    let text = this.data.com_content;
    let list = this.data.review_list;
    let cnt = this.data.review_count;
    wx.request({
      url:'http://127.0.0.1:3527/reviews/add',
      method:'POST',
      data:{
        "user_id":wx.getStorageSync('uid'),
        "post_id":pid,
        "review": text 
      },
      success(res){
        wx.request({
          url: `http://127.0.0.1:3527/reviews/get/${pid}`,
          method:'GET',
          success(res){
            setTimeout(()=>{
              console.log("AA")
            },1000)
            const processedList = res.data.data.map(item => {
              console.log(item);
              return {
                ...item, // 保留原始字段
                formatTime: formatTime(item.review_time) // 添加格式化时间字段
              };
            });
            that.setData({
              review_list:processedList,
              review_count:cnt+1,
              com_content:null
            });
          }
        })
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})